<?php
require_once '/home/ali0t4/source/waya/webroot/waya_api/application/libraries/wxinterface/Wxinterface.php';
require_once '/home/ali0t4/source/waya/webroot/waya_api/application/libraries/MySms.php';
class Wxcallbackapi
{
	//微信订阅号
	private $_appid="wx10cf4a129eb196fe";
	private $_appsecret="eede380fbbb23300924d4b151d815426";
	
	//验证消息
	public function valid()
	{
		$echoStr = $_GET["echostr"];
		if($this->checkSignature()){
			echo $echoStr;
			exit;
		}
	}

	//检查签名
	private function checkSignature()
	{
		$signature = $_GET["signature"];
		$timestamp = $_GET["timestamp"];
		$nonce = $_GET["nonce"];
		$token = "waya3dogs";
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode($tmpArr);
		$tmpStr = sha1($tmpStr);

		if($tmpStr == $signature){
			return true;
		}else{
			return false;
		}
	}

	//响应消息
	public function responseMsg()
	{
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		if (!empty($postStr)){
			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			$RX_TYPE = trim($postObj->MsgType);

			switch ($RX_TYPE)
			{
				case "event":
					$result = $this->receiveEvent($postObj);
					break;
				case "text":
					$result = $this->receiveText($postObj);
					break;
				case "image":
					$result = $this->receiveImage($postObj);
					break;
				case "video":
					$result = $this->receiveVideo($postObj);
					break;
				case "shortvideo":
					$result = $this->receiveVideo($postObj);
					break;
				case "voice":
					$result = $this->receiveVoice($postObj);
					break;
				case "location":
					$result= $this->receiveLocation($postObj);
					break;
				case "link":
					$result= $this->receiveLink($postObj);
					break;
				default:
					$result="";
					break;
					 
			}
			return $result;
		}else {
			return  "";
		}
	}
	private function receiveImage($object)
	{
		$content="这张照片真漂亮！";
		$result=$this->transmitText($object, $content);
		return $result;
	}

	private function receiveVideo($object)
	{
		$content="这个视频看上去好像挺有趣的！";
		$result=$this->transmitText($object, $content);
		return $result;
	}

	//接收事件消息
	private function receiveEvent($object)
	{
		switch ($object->Event)
		{
			case "subscribe":
				$content_gz = "Bonjour，欢迎加入哇吖的大家庭。哇吖由三位年轻的法国海龟创办于巴黎红山村（Montrouge Paris）的学生宿舍中。哇吖的理想是要打造最local的欧洲深度自由行&最fashion的上海轻度深体验。\n\n";
				$content_gz .= "自创立以来，在兼顾当地特色与价格的前提下，哇吖一直专注于为客人制定最个性化的旅游路线。从莫奈花园的写生，到居里夫人的实验室，从五渔村的秀丽，到伊瓦尔的精致，哇吖的努力总能为客人带来惊喜。\n\n";
				$content_gz .= "在上海，“城市探秘”是最能体现哇吖“旅行与社交”理念的产品。饱经风雨的古建筑，叱咤风云的历史人物，风趣幽默的真人NPC，开放式的故事情节...所有这些都是“哇吖·城市探秘”的标签！如何从时间与空间两个维度上感受上海，哇吖等你来挑战\n\n";
				$content_gz .= "总之，在哇吖就是要玩的嗨，玩得深，玩得嗨深！";
				$result=$this->transmitText($object, $content_gz);
				break;
			case "CLICK":
				if($object->EventKey=="b001_wayakefu")
				{
					$content_kf="请输入您想要询问的内容，哇吖将为您接入在线客服";
					$result=$this->transmitText($object, $content_kf);
					break;
				}
				if($object->EventKey=="treasure_hunter_act")
				{
					$data=array(array(
					'title'      => '哇吖城市探秘|消失的龟甲骨片（12月3日报名通道）',
					'description'=> '这是一部发生在上海的《西部世界》，这是一条充满着爱恨情仇的故事线。一张旧照片，半块龟甲骨片，尘封着怎样的真相',
					'picurl'     => 'http://mmbiz.qpic.cn/mmbiz_jpg/Pu3ufsdDcY1iahbK7oJYM5lma4Lib5XHCDxwoD1SSDsllcGy1d5vDAXiaO0ldQvMicIxSq221A4QrUgDfGxRrEPBibQ/640?wx_fmt=jpeg',
					'url'        => 'http://mp.weixin.qq.com/s/Ha4CLSlWle7WRC4wk9t5Qg'
					));
					$result=$this->transmitArticles($object, $data);
			        break;
				}
			default:
				$result="";
				break;
		}

		return $result;
	}

	//接收文本消息
	private function receiveText($object)
	{
		$object->Content =  trim($object->Content);
		if(in_array($object->Content, array('huaxue','hx','滑雪','ski'))){
			$data = array(array('title'=>'跟着哇吖去滑雪（2016.1.23-2016.2.3）','description'=>'哇吖自营出品，法国深度体验滑雪游（12天11晚），抓紧时间报名吧','picurl'=>'http://wayawc.sinaapp.com/ski.jpg','url'=>'http://mp.weixin.qq.com/s?__biz=MzIyNzExNDcxOA==&mid=405453310&idx=1&sn=dcf1277302d96bb49e16c7e01e247197#rd'));
			$result=$this->transmitArticles($object, $data);
		}
		//城市探秘报名 
		elseif (in_array($object->Content, array('城市探秘','城探','tanmi','chengshitanmi','chengtan'))){
			$data=array(array(
					'title'      => '哇吖城市探秘|消失的龟甲骨片（12月3日报名通道）',
					'description'=> '这是一部发生在上海的《西部世界》，这是一条充满着爱恨情仇的故事线。一张旧照片，半块龟甲骨片，尘封着怎样的真相',
					'picurl'     => 'http://mmbiz.qpic.cn/mmbiz_jpg/Pu3ufsdDcY1iahbK7oJYM5lma4Lib5XHCDxwoD1SSDsllcGy1d5vDAXiaO0ldQvMicIxSq221A4QrUgDfGxRrEPBibQ/640?wx_fmt=jpeg',
					'url'        => 'http://mp.weixin.qq.com/s/Ha4CLSlWle7WRC4wk9t5Qg'
			));
			$result=$this->transmitArticles($object, $data);
		}
		//城探过程工作人员短信提醒
		elseif (in_array($object->Content, array('pere','Pere','PERE','Père','père','PÈRE'))){
			//推送通知
			$time = date('Y-m-d H:i',time());
			$tpl_value = urlencode("#location#")."=".urlencode($time."电话亭");
	    	$mobile = "18321136597";
	    	$tpl_id = "1617900";
			$this->sendSms($tpl_id, $tpl_value, $mobile);
			$data=array(array(
					'title'      => '哇吖·城市探秘线索',
					'url'        => 'http://m.wayatrip.com/treasure_hunter/1/zhengci.html'
			));
			$result=$this->transmitArticles($object, $data);
		} 
		//城探场景背景推送
		elseif (in_array($object->Content, array('dbxs','dffd','dsj','eastindian','hjr','lsg','morse','pre','xbf','yh'))){
			switch ($object->Content)
			{
				case 'dbxs':
					$data=array(array(
							'title'      => '探秘背景-电报新书',
							'picurl'     => 'http://m.wayatrip.com/treasure_hunter/1/img/dbxs.png',
							'url'        => 'http://m.wayatrip.com/treasure_hunter/1/dbxs.html'
					));
					break;
				case 'dffd':
					$data=array(array(
							'title'      => '探秘背景-东方饭店',
							'picurl'     => 'http://m.wayatrip.com/treasure_hunter/1/img/dffd.png',
							'url'        => 'http://m.wayatrip.com/treasure_hunter/1/dffd.html'
					));
					break;
				case 'dsj':
					$data=array(array(
							'title'      => '探秘背景-大世界',
							'picurl'     => 'http://m.wayatrip.com/treasure_hunter/1/img/dsj.jpg',
							'url'        => 'http://m.wayatrip.com/treasure_hunter/1/dsj.html'
					));
					break;
				case 'eastindian':
					$data=array(array(
							'title'      => '探秘背景-法国东印度公司',
							'picurl'     => 'http://m.wayatrip.com/treasure_hunter/1/img/east_indian_1.png',
							'url'        => 'http://m.wayatrip.com/treasure_hunter/1/eastIndian.html'
					));
					break;
				case 'hjr':
					$data=array(array(
							'title'      => '探秘背景-黄金荣',
							'picurl'     => 'http://m.wayatrip.com/treasure_hunter/1/img/hjr_headimg.png',
							'url'        => 'http://m.wayatrip.com/treasure_hunter/1/hjr.html'
					));
					break;
				case 'lsg':
					$data=array(array(
							'title'      => '探秘背景-领事馆大道（Rue de Consulate）',
							'picurl'     => 'http://m.wayatrip.com/treasure_hunter/1/img/lsg_old.png',
							'url'        => 'http://m.wayatrip.com/treasure_hunter/1/lsg.html'
					));
					break;
				case 'morse':
					$data=array(array(
							'title'      => '探秘背景-摩斯电码',
							'picurl'     => 'http://m.wayatrip.com/treasure_hunter/1/img/morse_1.png',
							'url'        => 'http://m.wayatrip.com/treasure_hunter/1/morse.html'
					));
					break;
				case 'pre':
					$data=array(array(
							'title'      => '城市探秘-故事背景',
							'picurl'     => 'http://m.wayatrip.com/img/treasure_hunter/1/fazujie_map.png',
							'url'        => 'http://m.wayatrip.com/presentation.html'
					));
					break;
				case 'xbf':
					$data=array(array(
							'title'      => '探秘背景-霞飞路巡捕房',
							'picurl'     => 'http://m.wayatrip.com/treasure_hunter/1/img/xbf_old.png',
							'url'        => 'http://m.wayatrip.com/treasure_hunter/1/xbf.html'
					));
					break;
				case 'yh':
					$data=array(array(
							'title'      => '探秘背景-十里洋行',
							'picurl'     => 'http://m.wayatrip.com/treasure_hunter/1/img/yh_1.png',
							'url'        => 'http://m.wayatrip.com/treasure_hunter/1/yh.html'
					));
					break;
				default:
					return '';
					break;
			}
			if(!empty($data)){
				$result=$this->transmitArticles($object, $data);
			}
		}
		//转到客服
		else {
			$result=$this->transmitService($object);
		}
		
		return $result;
	}
	
	private function receiveVoice($object){
		$result=$this->transmitService($object);
		return $result;
	}
	
	private function receiveLocation($object){
		$content="为什么发给我坐标呢？如果有什么需要，请点击菜单栏客服哦！";
		$result=$this->transmitText($object, $content);
		return $result;
	}
	
	private function receiveLink($object)
	{
		$content="为什么发给我链接呢？如果有什么需要，请点击菜单栏客服哦！";
		$result=$this->transmitText($object, $content);
		return $result;
	}
	//------------------------------------------------------------
	private function transmitText($object, $content)
	{
		$xml = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[text]]></MsgType>
		<Content><![CDATA[%s]]></Content>
		</xml>";
		$result = sprintf($xml, $object->FromUserName, $object->ToUserName, time(), $content);
		return $result;
	}

	private function transmitMusic($object, $musicarr)
	{
		$item = "<Music>
	    <Title><![CDATA[%s]]></Title>
	    <Description><![CDATA[%s]]></Description>
	    <MusicUrl><![CDATA[%s]]></MusicUrl>
	    <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
		</Music>";

		$item_xml = sprintf($item, $musicarr['Title'], $musicarr['Description'], $musicarr['MusicUrl'], $musicarr['HQMusicUrl']);

		$xml = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[music]]></MsgType>
		$item_xml
		</xml>";

		$result = sprintf($xml, $object->FromUserName, $object->ToUserName, time());
		return $result;
	}
	private function transmitImage($object,$imgid)
	{
		$item="<Image><MediaId><![CDATA[%s]]></MediaId></Image>";
		$item_xml=sprintf($item,$imgid);
		$xml="<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[image]]></MsgType>
		$item_xml
		</xml>";
		$result = sprintf($xml, $object->FromUserName, $object->ToUserName, time());
		return $result;
	}
	private function transmitVideo($object,$videoarr)
	{
		$item="<Video><MediaId><![CDATA[%s]]></MediaId>
			<ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
			<Title><![CDATA[%s]]></Title>
			<Description><![CDATA[%s]]></Description></Video>";
    	$item_xml=sprintf($item,$videoarr['MediaId'],$videoarr['ThumbMediaId'],$videoarr['Title'],$videoarr['Description']);
    	$xml="<xml>
    	<ToUserName><![CDATA[%s]]></ToUserName>
    	<FromUserName><![CDATA[%s]]></FromUserName>
    	<CreateTime>%s</CreateTime>
    	<MsgType><![CDATA[video]]></MsgType>
    	$item_xml
    	</xml>";
    	$result = sprintf($xml, $object->FromUserName, $object->ToUserName, time());
    	return $result;

	}

	//回复多客服消息
	private function transmitService($object)
	{
		$xml= "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[transfer_customer_service]]></MsgType>
		</xml>";
        $result = sprintf($xml, $object->FromUserName, $object->ToUserName, time());
        return $result;
	}
	
	//检查客服是否在线
	private function checkOnlineKf()
	{
		$config = array("appid"=>$this->_appid,"appsecret"=>$this->_appsecret,"wxtype"=>'dingyu');
		$kf = new Wxinterface($config);
		
		$res = $kf->check_online_kf();
		$hasonlinekf = false;
		
		if(!empty($res['kf_online_list'])){
		    $hasonlinekf = true;
		}
		
		return $hasonlinekf;
	}

	private function transmitArticles($object,$data)
	{
		if(!isset($data) && empty($data)){
			return '';
	    }
		//导入图文数据
		/*$data=array(array(
				'title'      => '哇吖·城市探秘 | 上海滩杀人事件',
		'description'=> '100年前，法租界，预告的杀人案，档案馆，时空调查局（TBI），发迹前的黑帮大佬...是虚拟还是现实？是演绎',
		'picurl'     => 'https://mmbiz.qlogo.cn/mmbiz_jpg/Pu3ufsdDcY0O97jNtWW993WKiboPTjqIo9XpvR9kQxg51gH2aA54IhK9DmfX4oqYt1VPtEic47fxtSdFqFmvxxkA/0?wx_fmt=jpeg',
		'url'        => 'http://mp.weixin.qq.com/s?__biz=MzIyNzExNDcxOA==&mid=2656038215&idx=1&sn=d04f5ff0317a8b0d859bcce303a6bb5e&chksm=f3dd66f6c4aaefe0e86aafb6efe2a2c74adebf438b53287132290ac9a86d86f4064a77886e7b#rd'
		));*/
		$articles_count = count($data);
		//生成图文xml
		$item = "<item>
		<Title><![CDATA[%s]]></Title>
		<Description><![CDATA[%s]]></Description>
		<PicUrl><![CDATA[%s]]></PicUrl>
		<Url><![CDATA[%s]]></Url>
		</item>";
		$articles_xml = '';
    	foreach($data as $v){
    		$articles_xml .= sprintf($item,$v['title'],$v['description'],$v['picurl'],$v['url']);
    	}
    	//生成完整回复xml
		$xml = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[news]]></MsgType>
		<ArticleCount>%d</ArticleCount>
		<Articles>$articles_xml</Articles>
		</xml>";
		$result = sprintf($xml, $object->FromUserName, $object->ToUserName, time(),$articles_count);
		return $result;
	}
	
	private function sendSms($tpl_id, $tpl_value, $mobile)
	{
		$send =  new Mysms();
		$res = $send->tpl_send_sms($tpl_id, $tpl_value, $mobile);
		if($res['code']!=0){
			foreach($res as $k => $v){
				log_message('error',$k.'=>'.$v);
			}
		} else {
			log_message(error, "给".$res['mobile']."发送".$res['count']."条短信,模板id=".$tpl_id.",费用=".$res['fee']);
		}
	}
}